package com.lianxi.nmms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lianxi.nmms.constant.DeptConstant;
import com.lianxi.nmms.constant.DictConstant;
import com.lianxi.nmms.constant.ProductConstant;
import com.lianxi.nmms.constant.StatusConstant;
import com.lianxi.nmms.dao.DeptMapper;
import com.lianxi.nmms.dao.SequenceMapper;
import com.lianxi.nmms.entity.*;
import com.lianxi.nmms.exception.*;
import com.lianxi.nmms.service.DeptService;
import com.lianxi.nmms.util.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 翔哥
 * 2025年10月08日
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private SequenceMapper sequenceMapper;


    @Override
    public void addDept(String name, String remark, HttpSession session) throws RequestParameterErrorException, ProductTypeExistException, DeptExistException, loginErrorException {
        if (ParameterUtil.isNull(name) || ParameterUtil.isNull(remark)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        DeptExample deptExample = new DeptExample();
        deptExample.or()
                .andNameEqualTo(name);
        List<Dept> depts = deptMapper.selectByExample(deptExample);
        if (!depts.isEmpty()) {
            throw new DeptExistException("该部门已经存在了");
        }
        Dept dept = new Dept();
        dept.setName(name);
        dept.setRemark(remark);

        String NoName = DeptConstant.DEPT_FORMER;
        SequenceExample sequenceExample = new SequenceExample();
        sequenceExample.or()
                .andNameEqualTo(NoName);
        List<Sequence> sequences = sequenceMapper.selectByExample(sequenceExample);

        String no;
        if (sequences != null && !sequences.isEmpty()) {
            no = NoName + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ParameterUtil.getSequence(sequences.get(0).getValue());
            sequences.get(0).setValue(ParameterUtil.getSequence(sequences.get(0).getValue()));
            sequenceMapper.updateByPrimaryKeySelective(sequences.get(0));

        } else {
            Sequence sequence = new Sequence();
            sequence.setName(NoName);
            sequence.setValue(DeptConstant.DEPT_NO_MIN);
            sequenceMapper.insertSelective(sequence);
            no = NoName + new SimpleDateFormat("yyyyMMdd").format(new Date()) + DeptConstant.DEPT_NO_MIN;
        }
        dept.setNo(no);
        dept.setStatus(StatusConstant.DEPT_STATUS_ENABLED);
        dept.setCreateDate(new Date());
        Staff staff = (Staff) session.getAttribute("staff");
        if(staff ==null){
            throw new loginErrorException("还没有用户登录");
        }
        dept.setCreateStaffId(staff.getId());
        deptMapper.insertSelective(dept);
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public PageInfo<Dept> findPage(String pageNo, String pageSize) {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.PRODUCT_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.PRODUCT_DEFAULT_PAGE_SIZE;
        }

        PageHelper.startPage(Integer.valueOf(pageNo), Integer.valueOf(pageSize));
        List<Dept> depts = deptMapper.selectAll();
        PageInfo<Dept> deptPage = new PageInfo<>(depts);

        return deptPage;
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public List<Dept> findAll() {
        DeptExample deptExample =new DeptExample();
        return deptMapper.selectByExample(deptExample);
    }

    @Override
    public List<Dept> findStatus() {

        DeptExample deptExample =new DeptExample();
        deptExample.or()
                .andStatusEqualTo(StatusConstant.PRODUCT_TYPE_STATUS_ENABLED);
        return deptMapper.selectByExample(deptExample);
    }

    @Override
    public void addSonDept(String name, String remark, String fatherDeptId,HttpSession session) throws RequestParameterErrorException, DeptExistException, loginErrorException {
        if (ParameterUtil.isNull(name) || ParameterUtil.isNull(remark) || ParameterUtil.isNull(fatherDeptId)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        DeptExample deptExample = new DeptExample();
        deptExample.or()
                .andNameEqualTo(name);
        List<Dept> depts = deptMapper.selectByExample(deptExample);
        if (!depts.isEmpty()) {
            throw new DeptExistException("该部门已经存在了");
        }
        Dept dept = new Dept();
        dept.setName(name);
        dept.setRemark(remark);

        String NoName = DeptConstant.DEPT_FORMER;
        SequenceExample sequenceExample = new SequenceExample();
        sequenceExample.or()
                .andNameEqualTo(NoName);
        List<Sequence> sequences = sequenceMapper.selectByExample(sequenceExample);

        String no;
        if (sequences != null && !sequences.isEmpty()) {
            no = NoName + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ParameterUtil.getSequence(sequences.get(0).getValue());
            sequences.get(0).setValue(ParameterUtil.getSequence(sequences.get(0).getValue()));
            sequenceMapper.updateByPrimaryKeySelective(sequences.get(0));

        } else {
            Sequence sequence = new Sequence();
            sequence.setName(NoName);
            sequence.setValue(DeptConstant.DEPT_NO_MIN);
            sequenceMapper.insertSelective(sequence);
            no = NoName + new SimpleDateFormat("yyyyMMdd").format(new Date()) + DeptConstant.DEPT_NO_MIN;
        }
        dept.setNo(no);
        dept.setStatus(StatusConstant.DEPT_STATUS_ENABLED);
        dept.setCreateDate(new Date());
        Staff staff = (Staff) session.getAttribute("staff");
        if(staff ==null){
            throw new loginErrorException("还没有用户登录");
        }
        dept.setCreateStaffId(staff.getId());
        dept.setFatherDeptId(Integer.valueOf(fatherDeptId));
        deptMapper.insertSelective(dept);
    }

    @Override
    public Dept findDeptById(String id) throws RequestParameterErrorException {
        if(ParameterUtil.isNull(id)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        Dept dept = deptMapper.selectByPrimaryKey(Integer.valueOf(id));
        return dept;
    }

    @Override
    public void updateDept(String id,String name, String remark) throws RequestParameterErrorException, DeptExistException {
        if(ParameterUtil.isNull(name)||ParameterUtil.isNull(remark)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        DeptExample deptExample =new DeptExample();
        deptExample.or()
                .andIdEqualTo(Integer.valueOf(id));
        List<Dept> depts = (List<Dept>) deptMapper.selectByExample(deptExample);
        if ((depts.isEmpty())){
            throw new DeptExistException("该部门不存在");
        }
        Dept dept =depts.get(0);
        dept.setName(name);
        dept.setRemark(remark);
        deptMapper.updateByPrimaryKey(dept);
    }

    @Override
    public void enableDept(String id) throws RequestParameterErrorException, DeptStatusErrorException {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        Dept dept = findDeptById(id);
        if(dept.getFatherDeptId()!=null){
           Dept fatherDept =deptMapper.selectByPrimaryKey(dept.getFatherDeptId());
            if (fatherDept.getStatus()==StatusConstant.DEPT_STATUS_DISABLED){
                throw new DeptStatusErrorException("请先启用上级部门");
            }else {
                dept.setStatus(StatusConstant.DEPT_STATUS_ENABLED);
            }
        }else {
            dept.setStatus(StatusConstant.DEPT_STATUS_ENABLED);
        }
        deptMapper.updateByPrimaryKeySelective(dept);
    }

    @Override
    public void disableDept(String id) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        Dept dept = findDeptById(id);
        dept.setStatus(StatusConstant.DEPT_STATUS_DISABLED);
        deptMapper.updateByPrimaryKeySelective(dept);

        DeptExample deptExample =new DeptExample();
        deptExample.or()
                .andFatherDeptIdEqualTo(Integer.valueOf(id));
        List<Dept> depts =deptMapper.selectByExample(deptExample);
        for (Dept d:depts){
            disableDept(d.getId().toString());
        }
    }
}
